<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>自主对话系统测试</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 20px;
            background-color: #f0f0f0;
        }
        .container {
            max-width: 800px;
            margin: 0 auto;
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        .test-section {
            margin: 20px 0;
            padding: 15px;
            border: 1px solid #ddd;
            border-radius: 5px;
        }
        .test-button {
            background: #4CAF50;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 4px;
            cursor: pointer;
            margin: 5px;
        }
        .test-button:hover {
            background: #45a049;
        }
        .log {
            background: #f9f9f9;
            border: 1px solid #ddd;
            padding: 10px;
            margin: 10px 0;
            border-radius: 4px;
            max-height: 300px;
            overflow-y: auto;
            font-family: monospace;
            font-size: 12px;
        }
        .entity-info {
            background: #e7f3ff;
            padding: 10px;
            margin: 10px 0;
            border-radius: 4px;
        }
        .debug-info {
            background: #fff3cd;
            padding: 10px;
            margin: 10px 0;
            border-radius: 4px;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>自主对话系统测试</h1>
        
        <div class="test-section">
            <h3>1. 基础功能测试</h3>
            <button class="test-button" onclick="testAutoChat()">测试自主对话触发</button>
            <button class="test-button" onclick="testPersonality()">测试个性化回复</button>
            <button class="test-button" onclick="testCooldown()">测试冷却机制</button>
            <div id="basicLog" class="log"></div>
        </div>

        <div class="test-section">
            <h3>2. 实体状态监控</h3>
            <button class="test-button" onclick="showEntityStates()">显示实体状态</button>
            <button class="test-button" onclick="resetCooldowns()">重置冷却时间</button>
            <div id="entityStates" class="entity-info"></div>
        </div>

        <div class="test-section">
            <h3>3. 调试信息</h3>
            <button class="test-button" onclick="showDebugInfo()">显示调试信息</button>
            <div id="debugInfo" class="debug-info"></div>
        </div>

        <div class="test-section">
            <h3>4. 模拟玩家移动</h3>
            <button class="test-button" onclick="simulatePlayerApproach()">模拟玩家接近</button>
            <button class="test-button" onclick="simulatePlayerLeave()">模拟玩家离开</button>
            <div id="simulationLog" class="log"></div>
        </div>
    </div>

    <script type="module">
        import { AutoChatManager } from './src/chat/AutoChatManager.js';
        import { getEntityPersona } from './src/chat/EntityPersonas.js';

        // 模拟实体类
        class MockEntity {
            constructor(id, type, position) {
                this.id = id;
                this.type = type;
                this.position = position;
                this.alive = true;
            }

            getId() { return this.id; }
            getType() { return this.type; }
            getPosition() { return this.position; }
            isAlive() { return this.alive; }
        }

        // 创建自主对话管理器
        const autoChatManager = new AutoChatManager();
        
        // 创建模拟实体
        const entities = [
            new MockEntity('cow1', 'cow', { x: 5, y: 0, z: 5 }),
            new MockEntity('pig1', 'pig', { x: -3, y: 0, z: 8 }),
            new MockEntity('sheep1', 'sheep', { x: 10, y: 0, z: -2 })
        ];

        let playerPosition = { x: 0, y: 0, z: 0 };

        // 设置游戏上下文提供者
        autoChatManager.setGameContextProvider((entity) => ({
            playerPosition,
            timeOfDay: 'noon',
            weather: 'clear',
            nearbyBlocks: ['grass', 'dirt'],
            nearbyEntities: ['cow', 'pig']
        }));

        // 设置自主对话回调
        autoChatManager.setOnAutoChatCallback((entity, message) => {
            log('basicLog', `🗨️ ${entity.getType()} (${entity.getId()}) 说: "${message}"`);
        });

        // 日志函数
        function log(elementId, message) {
            const logElement = document.getElementById(elementId);
            const timestamp = new Date().toLocaleTimeString();
            logElement.innerHTML += `[${timestamp}] ${message}\n`;
            logElement.scrollTop = logElement.scrollHeight;
        }

        // 测试函数
        window.testAutoChat = function() {
            log('basicLog', '🧪 开始测试自主对话触发...');
            
            // 模拟玩家接近实体
            playerPosition = { x: 6, y: 0, z: 6 }; // 接近cow1
            
            // 更新自主对话系统
            autoChatManager.update(playerPosition, entities);
            
            log('basicLog', `📍 玩家移动到位置: (${playerPosition.x}, ${playerPosition.y}, ${playerPosition.z})`);
        };

        window.testPersonality = function() {
            log('basicLog', '🎭 测试个性化回复...');
            
            entities.forEach(entity => {
                const persona = getEntityPersona(entity.getType());
                if (persona) {
                    log('basicLog', `${entity.getType()}: ${persona.personality}`);
                }
            });
        };

        window.testCooldown = function() {
            log('basicLog', '⏰ 测试冷却机制...');
            
            // 重置冷却时间
            entities.forEach(entity => {
                autoChatManager.resetEntityCooldown(entity.getId());
            });
            
            // 连续触发多次
            for (let i = 0; i < 3; i++) {
                setTimeout(() => {
                    autoChatManager.update(playerPosition, entities);
                    log('basicLog', `第 ${i + 1} 次触发尝试`);
                }, i * 1000);
            }
        };

        window.showEntityStates = function() {
            const debugInfo = autoChatManager.getDebugInfo();
            const statesDiv = document.getElementById('entityStates');
            
            let html = '<h4>实体状态:</h4>';
            debugInfo.entityStates.forEach(state => {
                html += `
                    <div style="margin: 10px 0; padding: 10px; border: 1px solid #ccc; border-radius: 4px;">
                        <strong>实体ID:</strong> ${state.entityId}<br>
                        <strong>上次对话:</strong> ${state.lastChatTime}<br>
                        <strong>在范围内:</strong> ${state.isInRange ? '是' : '否'}<br>
                        <strong>已问候:</strong> ${state.hasGreeted ? '是' : '否'}<br>
                        <strong>冷却剩余:</strong> ${Math.round(state.cooldownRemaining / 1000)}秒
                    </div>
                `;
            });
            
            statesDiv.innerHTML = html;
        };

        window.resetCooldowns = function() {
            entities.forEach(entity => {
                autoChatManager.resetEntityCooldown(entity.getId());
            });
            log('basicLog', '🔄 已重置所有实体的冷却时间');
        };

        window.showDebugInfo = function() {
            const debugInfo = autoChatManager.getDebugInfo();
            const debugDiv = document.getElementById('debugInfo');
            
            debugDiv.innerHTML = `
                <h4>调试信息:</h4>
                <p><strong>检测范围:</strong> ${debugInfo.detectionRange} 格</p>
                <p><strong>冷却时间:</strong> ${debugInfo.cooldownDuration / 1000} 秒</p>
                <p><strong>跟踪实体数:</strong> ${debugInfo.trackedEntities}</p>
                <pre>${JSON.stringify(debugInfo, null, 2)}</pre>
            `;
        };

        window.simulatePlayerApproach = function() {
            log('simulationLog', '🚶 模拟玩家接近实体...');
            
            // 逐步接近cow1
            const targetEntity = entities[0]; // cow1
            const steps = 5;
            
            for (let i = 0; i < steps; i++) {
                setTimeout(() => {
                    const progress = (i + 1) / steps;
                    playerPosition = {
                        x: targetEntity.position.x * progress,
                        y: 0,
                        z: targetEntity.position.z * progress
                    };
                    
                    const distance = Math.sqrt(
                        Math.pow(playerPosition.x - targetEntity.position.x, 2) +
                        Math.pow(playerPosition.z - targetEntity.position.z, 2)
                    );
                    
                    log('simulationLog', `步骤 ${i + 1}: 玩家位置 (${playerPosition.x.toFixed(1)}, ${playerPosition.z.toFixed(1)}), 距离: ${distance.toFixed(1)}`);
                    
                    autoChatManager.update(playerPosition, entities);
                }, i * 500);
            }
        };

        window.simulatePlayerLeave = function() {
            log('simulationLog', '🚶‍♂️ 模拟玩家离开...');
            
            // 逐步远离
            const steps = 5;
            
            for (let i = 0; i < steps; i++) {
                setTimeout(() => {
                    playerPosition = {
                        x: playerPosition.x + 5,
                        y: 0,
                        z: playerPosition.z + 5
                    };
                    
                    log('simulationLog', `步骤 ${i + 1}: 玩家位置 (${playerPosition.x}, ${playerPosition.z})`);
                    
                    autoChatManager.update(playerPosition, entities);
                }, i * 500);
            }
        };

        // 自动开始测试
        setTimeout(() => {
            log('basicLog', '🎮 自主对话系统测试页面已加载');
            log('basicLog', '💡 点击按钮开始测试各项功能');
        }, 100);
    </script>
</body>
</html>